package com.test17.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ResourceBundle;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

/**
 * 可以用来压缩文件
 * @author tdp
 *
 */
/**
 * encoding一定要设置成GBK，才能争取使用中文，不知道为什么
 * @author wangquan
 *
 */
public class ZipWrap{
	private static String tempDir = ResourceBundle.getBundle("ftp").getString("zip.temp");
	private static String encoding = ResourceBundle.getBundle("ftp").getString("zip.encoding");
	private ZipOutputStream zipOutputStream = null;
	private File createTempFile = null;
	/**
	 * 构造创建临时文件
	 */
	public ZipWrap() {
		try {
			createTempFile = File.createTempFile(RandomStringUtils.randomAlphabetic(10),".ziptmp",new File(tempDir));
			createTempFile.deleteOnExit();
			this.zipOutputStream = new ZipOutputStream(createTempFile);
			this.zipOutputStream.setEncoding(encoding);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 追加文件
	 * @param inputStream
	 * @param path
	 * @param filename
	 */
	public void addInputStream(InputStream inputStream, String path, String filename) {
		try {
			zipOutputStream.putNextEntry(new ZipEntry(path + File.separator + filename));
			byte[] bys = new byte[2048];
			int len = -1;
			while ((len = inputStream.read(bys)) != -1) {
				zipOutputStream.write(bys, 0, len);
			}
			zipOutputStream.closeEntry();
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void addFile(File file,String path,String filename){
//		如果不存在或不是文件就直接返回
		if (!file.exists()||file.isDirectory()) {
			return;
		}
		try {
			this.addInputStream(new FileInputStream(file), path, filename);
		} catch (FileNotFoundException e) {
		}
	}
	/**
	 * 获取zip文件的流
	 * @return
	 */
	public InputStream getZip(){
		try {
			zipOutputStream.finish();
			return new FileInputStream(this.createTempFile);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
